import http from '@/shopro/request/index'
import https from '@/shopro/requests/index'
import share from '@/shopro/share';
import Auth from '@/shopro/permission/index.js';
import qqmapsdk from '@/shopro/mixins/qqmap-wx-jssdk.min.js';
const QQMapWX = new qqmapsdk({
	key: '34GBZ-ZG66D-KV54R-P3DBA-L5F6O-QQFOT' //开发者密钥 腾讯地图key
});
const state = {
	shop: {}, // 商城信息
	wechat: {}, // 微信配置
	share: {}, // 分享配置
	payment: {}, // 支付配置
	addons: [], // 插件配置
	chat: uni.getStorageSync("chat") || {}, // 客服配置
	store: {}, // 商城信息
	tabbarData: [], //自定义底部导航数据

	homeTemplate: [], // 首页模板数据
	userTemplate: [], // 个人中心模板数据
	floatData: {}, // 悬浮按钮数据
	popupData: {}, // 弹窗数据
	hasTemplate: true, //是否有模板数据
	shareInfo: {}, // 默认分享数据
	latitude:uni.getStorageSync("latitude") || "",//纬度
	longitude:uni.getStorageSync("longitude") || "",//经度
	citys:uni.getStorageSync("city") || "",//城市名称
	//拼团要用到的参数
	is_join:'',  //是否参团
	vip_pink_id:'', //拼团的id
	vip_pink_status:'', //这个团目前的状态
	typeTitle:'', //1  拼团   2  砍价   判断拼团详情页面和砍价详情页面的标题
	pink_time:'' //这个拼团的倒计时
}
const getters = {
	initShop: state => state.shop,
	initStore: state => state.store,
	initShare: state => state.share,
	initPayment: state => state.payment,
	initAddons: state => state.addons,
	initChat: state => state.chat,
	initWechat: state => state.wechat,

	hasTemplate: state => state.hasTemplate,
	homeTemplate: state => state.homeTemplate,
	userTemplate: state => state.userTemplate,
	floatData: state => state.floatData,
	popupData: state => state.popupData,
	tabbarData: state => state.tabbarData,

	shareInfo: state => state.shareInfo,
	latitude: state => state.latitude,
	longitude: state => state.longitude,
	citys:state=> state.citys,
	is_join:state=>state.is_join,
	vip_pink_id:state=>state.vip_pink_id,
	vip_pink_status:state=>state.vip_pink_status,
	typeTitle:state=>state.typeTitle,
	pink_time:state=>state.pink_time
}


const actions = {
	//如果是拼团进入页面 开启定时任务
	async setTimecantuan({
		state,
		commit,
		 dispatch,
		getters
	}, options){
		if (uni.getStorageSync("vip_pink_id")!='0'&& uni.getStorageSync("typeTitle")=='1') {
			let timer = null;
			https('vip.pinklists_detail', {
				token:uni.getStorageSync("token"),
				id:uni.getStorageSync("vip_pink_id"),
			}).then(resPinkInfo => {
				if(resPinkInfo.code == '1'){
					if(!resPinkInfo.data.pink||resPinkInfo.data.pink.times<=0||resPinkInfo.data.is_join=='1'){
						clearInterval(timer)
					}
					commit('SET_STATUS', resPinkInfo.data);
				}
			})
			clearInterval(timer);
			timer = setInterval(()=>{
				https('vip.pinklists_detail', {
					token:uni.getStorageSync("token"),
					id:uni.getStorageSync("vip_pink_id"),
				}).then(resPinkInfo => {
					if(resPinkInfo.code == '1'){
						if(!resPinkInfo.data.pink||resPinkInfo.data.pink.times<=0){
							clearInterval(timer)
						}
					    commit('SET_STATUS', resPinkInfo.data);
					}
				})
			},10000)
		}

	},
	// 地址选择
	async locationAddress({
		  commit
	  }, options){
		  console.log("用户授权了位置")
		  uni.getLocation({
		  	type: "wgs84", //默认为 wgs84 返回 gps 坐标
		  	geocode: "true",
		  	isHighAccuracy: "true",
		  	accuracy: "best",
		  	success: res => {
		  		let locationModel = {
		  			latitude: res.latitude,
		  			longitude: res.longitude
		  		}
		  
		  		uni.setStorageSync("latitude", res.latitude);
		  		uni.setStorageSync("longitude", res.longitude);
		  		// 解析地址
		  		QQMapWX.reverseGeocoder({
		  			location: {
		  				latitude: res.latitude,
		  				longitude: res.longitude
		  			},
		  			success: function (res1) {
		  				console.log('解析地址成功');
		  				console.log(res1);
		  				// 省
		  				// let province = res.result.ad_info.province;
		  				// 市
		  				let city = res1.result.ad_info.city;
		  				uni.setStorageSync("city", city);
		  				locationModel.citys = city;
		  				commit('LOCATION_MODEL', locationModel);
		  			},
		  			fail: function (res2) {
		  				uni.showToast({
		  					title: '定位失败',
		  					duration: 2000,
		  					icon: 'none'
		  				});
		  				console.log(res2);
		  			},
		  			complete: function (res3) { //无论成功失败都会执行
		  				console.log(res3);
		  			}
		  		});
		  	},
		  	fail: err => {
		  		console.log("￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥");
		  		console.log(err);
		  	}
		  });
		// uni.authorize({
		// 	scope: 'scope.userLocation',
		// 	success() {
				
		// 	}
		// })
	},
	// 初始化数据
	async appInit({
		commit,
		dispatch
	}, options) {
		const result = await http('common.init');
		if (result.code === 1) {
			commit('CONFIG', result.data);
			if (!options?.query?.token) {
				dispatch('autoLogin');
			}
			return result.data;
		}
		return false;
	},

	// 获取模板数据
	async getTemplate({
		dispatch,
		commit
	}, options) {
		console.log("========2222")
		let shop_id = 0;
		// #ifdef H5
		if (options?.query.shop_id) {
			shop_id = options.query.shop_id;
		}
		// #endif

		// #ifdef MP
		if (options?.query.scene) {
			let scene = decodeURIComponent(options?.query.scene);
			let sceneObj = scene.split('=');
			if (sceneObj[0] === 'shop_id') {
				shop_id = sceneObj[1]
			}
		}
		// #endif
		const result = await http('common.template', shop_id ? {
			shop_id
		} : {});
		if (result.code === 1) {
			commit("hasTemplate", true);
			const result_index = await https('common.template_index', {
				'latitude':uni.getStorageSync("latitude") || "",//纬度
				'longitude':uni.getStorageSync("longitude") || "",//经度
				"token":uni.getStorageSync("token")||''
			});
			let data = {
				"home": [
					{
						"id": 15424,
						"type": "menu",
						"category": "home",
						"name": "菜单组",
						"content": {
							"name": "",
							"style": 4,
							"list": []
						},
						"decorate_id": 1
					},
					{
						"id": 15423,
						"type": "banner",
						"category": "home",
						"name": "轮播图",
						"content": {
							"name": "",
							"style": 1,
							"height": 120,
							"radius": 10,
							"x": 20,
							"y": 10,
							"list": []
						},
						"decorate_id": 1
					},
					{
						"id": 15427,
						"type": "groupon",
						"category": "home",
						"name": "秒杀",
						"content": {
							"id": 2,
							"name": "特价拼团",
							"style": 1,
							"groupon_name": "拼团专场",
							"team_num": "3"
						},
						"decorate_id": 1
					},
					{
						"id": 15431,
						"type": "category-tabs",
						"category": "home",
						"name": "分类选项卡",
						"content": {
							"ids": "'',69,70,71,72",
							"category_arr": [
								{
									"id": 44,
									"name": "商帮商邦",
									"type": "",
									"image": "http://file.shopro.top/uploads/20210519/b505c4c6c4aefdb3467877f2ef21c534.jpeg",
									"pid": 43,
									"weigh": 0,
									"description": "",
									"status": "normal",
									"createtime": 1621406730,
									"updatetime": 1650699272,
									"children": []
								},
								{
									"id": 69,
									"name": "商帮惠选",
									"type": "",
									"image": "http://file.shopro.top/uploads/20210519/b330cd09cd55c038c1743aef21545241.png",
									"pid": 43,
									"weigh": 0,
									"description": "",
									"status": "normal",
									"createtime": 1621407282,
									"updatetime": 1650699272,
									"children": []
								},
								{
									"id": 70,
									"name": "米包多多",
									"type": "",
									"image": "http://file.shopro.top/uploads/20210519/225422d99ca344883fc5a1a52a6f2ad5.png",
									"pid": 43,
									"weigh": 0,
									"description": "",
									"status": "normal",
									"createtime": 1621407282,
									"updatetime": 1650699272,
									"children": []
								},
							],
							"style": 2
						},
						"decorate_id": 1
					}
				],
				"popup": [
					{
						"id": 15432,
						"type": "popup",
						"category": "popup",
						"name": "弹窗提醒",
						"content": {
							"list": [
								{
									"name": "",
									"style": 1,
									"image": "http://file.shopro.top/uploads/20210518/9136ecddcddf6607184fab689207e7e3.png",
									"btnimage": "",
									"path": "/pages/app/coupon/list",
									"path_name": "优惠券中心",
									"path_type": 1
								}
							]
						},
						"decorate_id": 1
					}
				],
			}
			data.home.forEach((item,index)=>{
				if(item.type == 'banner'){
					item.content.list = result_index.data.lunbo;
				}
				if(item.type == 'menu'){
					item.content.list = result_index.data.cate;
				}
				if(item.type == 'groupon'){
					item.content.list = result_index.data.miaosha;
				}
				if(item.type == 'category-tabs'){
					item.content.category_arr[0].children = result_index.data.shangbang;
					item.content.category_arr[1].children = result_index.data.huixuan;
					item.content.category_arr[2].children = result_index.data.mibao;
				}
			})
			commit('TEMPLATE', data);
			return data;
		} else {
			commit("hasTemplate", false);
			return false;
		}
		if(uni.getStorageSync('isLogin')){
			await https('user.info').then(res => {
				if (res.code === 1) {
					let lastLoginStatus = uni.getStorageSync('isLogin');
					uni.setStorageSync('userInfo',res.data)
					lastLoginStatus && share.setShareInfo({params:res.data});
					// 存在分享信息 添加分享记录
					let spm = uni.getStorageSync('spm');
					if (spm) {
						http('common.shareAdd', {
							spm: spm
						});
						uni.removeStorageSync('spm');
					}
				}

			})
		}

	},

	// 同步路由到后端
	syncPages({
		commit
	}) {
		http('common.syncPages', {
			data: ROUTES,
		})
	},
	changecity({
		dispatch,
		  commit
    }, options){
		options.latitude = options.lat;
		options.longitude = options.lng;
		options.citys = options.name;
		uni.setStorageSync("latitude", options.latitude);
		uni.setStorageSync("longitude", options.longitude);
		uni.setStorageSync("city", options.name);
		commit('LOCATION_MODEL', options);
	},
}


const mutations = {
	LOCATION_MODEL(state, data){
		state.latitude = data.latitude;
		state.longitude = data.longitude;
		state.citys = data.citys;
		console.log("loactiondata==========",state)
	},
	CONFIG(state, payload) {
		Object.keys(payload).forEach(k => {
			state[k] = payload[k];
			if (k === 'chat') {
				uni.setStorageSync("chat", payload[k]);
			}
		})
	},

	TEMPLATE(state, data) {
		state.template = data;
		state.homeTemplate = data.home
		state.userTemplate = data.user
		state.floatData = data['float-button']?. [0]?.content
		state.popupData = data?.popup?. [0]?.content
		state.tabbarData = data?.tabbar?. [0]?.content
	},

	hasTemplate(state, data) {
		state.hasTemplate = data
	},
	// 弹窗一次的话，关闭的时候删除数据。
	delPopup(state, index) {
		let popupData = state.popupData;
		popupData.list.splice(index, 1)
		state.template = popupData;
	},
	shareInfo(state, shareInfo) {
		state.shareInfo = shareInfo;
	},
	SET_STATUS(state,resPinkInfo){
		if(resPinkInfo){
			state.is_join = resPinkInfo.is_join
			state.vip_pink_id = resPinkInfo.pink.vip_pink_id
			state.pink_time = resPinkInfo.pink.times
			console.log("state*******state:",state)
		}
	},
}


export default {
	state,
	mutations,
	actions,
	getters
}
